﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Entity;
using EF.DAL;

namespace EF.DAL
{
    public abstract class RepositoryBase<T>:IRepository<T> where T :class,new()
    {
        public DbContext context;

        //提供IOC注入方式接口
        public RepositoryBase(DemoDBEntities context)
        {
            this.context = context;  
        }

        //测试用
        public RepositoryBase()
        {
            this.context = new DemoDBEntities();
        }

        #region IRepository<T> 成员

        public T Create()
        {
            return context.Set<T>().Create();
        }

        public T Update(T entity)
        {
            //执行验证业务
            //context.Entry<T>(entity).GetValidationResult();
            if (context.Entry<T>(entity).State == EntityState.Modified)             
                context.SaveChanges();
            return entity;
        }

        public T Insert(T entity)
        {
            context.Set<T>().Add(entity);
            context.SaveChanges();
            return entity;
        }

        public void Delete(T entity)
        {
            context.Set<T>().Remove(entity);
            context.SaveChanges();
        }

        public T Find(params object[]keyValues)
        {
            return context.Set<T>().Find(keyValues);
        }

        public List<T> FindAll()
        {
            return context.Set<T>().ToList();
        }

        #endregion
    }
}
